window.onload = function () {
  const canvas = document.querySelector("#canvas");
  canvas.width = 400;
  canvas.height = 300;

  const n = 20;
  const array = [];
  const margin = 30; // 画布边距
  const gap = 4; // 柱子间距

  const cols = [];
  const spacing = (canvas.width - margin * 2) / n;
  const ctx = canvas.getContext("2d");

  const maxColumnHeight = 200;

  let moves = [];
  let audioCtx = null;

  // freq 频率
  function playNote(freq, type = "sine") {
    if (audioCtx == null) {
      audioCtx = new AudioContext();
    }
    window.aa = audioCtx;

    const dur = 0.2;
    const osc = audioCtx.createOscillator();
    osc.frequency.value = freq;
    osc.start();
    osc.type = type;
    osc.stop(audioCtx.currentTime + dur);

    const node = audioCtx.createGain();
    node.gain.value = 0.4;
    node.gain.linearRampToValueAtTime(0, audioCtx.currentTime + dur);

    osc.connect(node);
    node.connect(audioCtx.destination);
  }

  function init() {
    // console.log("init");
    for (let i = 0; i < n; i++) {
      array[i] = Math.random();
    }
    moves = [];

    for (let i = 0; i < array.length; i++) {
      const x = i * spacing + spacing / 2 + margin;
      // const y = canvas.height - margin;
      const y = canvas.height - margin - i * 3; // 倾斜感觉
      const width = spacing - gap;
      const height = maxColumnHeight * array[i];
      cols[i] = new Column(x, y, width, height);
      cols[i].draw(ctx);
    }
  }
  function play() {
    // console.log("play");
    moves = bubbleSort(array);
  }

  document.getElementById("init").onclick = init;
  document.getElementById("play").onclick = play;

  init();
  // play();

  animate();

  function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    let changed = false;
    for (let i = 0; i < cols.length; i++) {
      changed = cols[i].draw(ctx) || changed;
    }

    // 调用移动函数，将需要排序的柱子进行移动
    if (!changed && moves.length > 0) {
      const move = moves.shift();
      const [i, j] = move.indices;

      const waveformType = move.swap ? "sine" : "square";
      playNote(cols[i].height + cols[j].height, waveformType);

      if (move.swap) {
        cols[i].moveTo(cols[j], 1); // 1 交换的偏移量动画，默认是 1
        cols[j].moveTo(cols[i], -1); // -1 交换的偏移量动画，默认是 1
        [cols[i], cols[j]] = [cols[j], cols[i]];
      } else {
        // 不用交换
        cols[i].jump();
        cols[j].jump();
      }
    }

    // console.log("run...");
    requestAnimationFrame(animate);
  }
};
